package com.woniuxy.main.realm;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.woniuxy.main.pojo.User;
import com.woniuxy.main.service.UserService;
import com.woniuxy.main.util.SessionUtil;


public class UserRealm extends AuthorizingRealm{
	@Resource
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//System.out.println("正在授权");
		//获取uid
		Session session =SessionUtil.getSession();
		String str =session.getAttribute("uid").toString();
		int uid =Integer.parseInt(str);
		//获取用户的角色
		String userRole=userService.selectByUid(uid).getUserRole();	
		//创建集合保存身份
		Set<String> roles =new HashSet<>();
		roles.add(userRole);
		SimpleAuthorizationInfo info =new SimpleAuthorizationInfo(roles);
		return info;
	}
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//System.out.println("正在认证"+token);
		//获取账号
		String account = (String) token.getPrincipal();
		//根据账号查询该对象
		User newUser =null;
		newUser= userService.selectByAccount(account);
		//账号为空,用手机去查
		if(newUser==null){
			newUser=userService.selectByPhone(account);
		}
		//手机和账号为空,邮箱去查
		if(newUser==null){
			newUser=userService.selectByMail(account);
		}
		//如果还是没有，代表没有此账户
		if(newUser==null){
			return null;
		}
		//存入uid到session
		Session session =SessionUtil.getSession();
		session.setAttribute("uid", newUser.getUid());
		//存入地址到session
		session.setAttribute("address", newUser.getAddress());
		session.setAttribute("userRole", newUser.getUserRole());
		//获取盐值
		ByteSource salt =ByteSource.Util.bytes(newUser.getAccount());	
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(newUser.getAccount(),newUser.getPwd(),salt,getName());	
		//System.out.println("info:"+info);		
		return info;
	}
	
}
